import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../model/PPShopHomePageModel.dart';

class PPSwiperView extends StatefulWidget {

    PPSwiperView(List<PPShopPlateContent> data, {
        Key key, 
        this.h = 200, 
        this.autoplay = true,
        this.onPressAction,
        this.onIndexChangedAction,
    }): this.data = data, super(key: key);

    final List<PPShopPlateContent> data;
    final double h;
    final Function onPressAction;
    final Function onIndexChangedAction;
    final bool autoplay;

    _PPSwiperViewState createState() => _PPSwiperViewState();
}

class _PPSwiperViewState extends State<PPSwiperView> {

    List<PPShopPlateContent> data;
    double height;
    bool autoplay;

    @override
    void initState() {
        data = widget.data;
        height = widget.h;
        autoplay = widget.autoplay;
        super.initState();
    }

    @override
    void didUpdateWidget(PPSwiperView oldWidget) {
        data = widget.data;
        height = widget.h;
        super.didUpdateWidget(oldWidget);
    }

    @override
    Widget build(BuildContext context) {
        if(data == null || data.length == 0) {
            return null;
        } else {
            return (Container(
                width: MediaQuery.of(context).size.width,
                height: height,
                child: Swiper(
                    itemBuilder: (BuildContext context, int index){
                        PPShopPlateContent item = data[index];
                        return item != null && item.url != null ? Image.network(item.url) : null;
                    },
                    loop: true,
                    autoplay: true,
                    itemCount: data.length,
                    pagination: SwiperPagination(
                        margin: EdgeInsets.fromLTRB(0,0,20,15),
                        builder: DotSwiperPaginationBuilder(color: Colors.black54, activeColor: Colors.white)
                    ),
                    controller: SwiperController(),
                    scrollDirection: Axis.horizontal,
                    onTap: _onPressAction,
                    onIndexChanged: _onIndexChangedAction,
                ))
            );  
        }
    }

    _onPressAction(index) {
        if(widget.onPressAction != null) {
            widget.onPressAction(index);
        }
    }

    _onIndexChangedAction(value) {
        if(widget.onIndexChangedAction != null) {
            widget.onIndexChangedAction(value);
        }
    }
}
 